<template>
  <div class="personal">
    <h1>个人资料</h1>

    <el-card>
      <el-menu
        :default-active="activeIndex"
        class="el-menu-demo"
        mode="horizontal"
        @select="handleSelect"
      >
        <el-menu-item index="0">个人资料</el-menu-item>
        <el-menu-item index="1">修改密码</el-menu-item>
      </el-menu>
      <!-- 个人资料区域 -->
      <el-form
        v-show="this.menuIndex === '0'"
        ref="personalFormRef"
        :rules="personalFormRules"
        :model="personalForm"
        label-width="80px"
      >
        <el-form-item label="用户头像">
          <!-- <el-input v-model="personalForm.userimg"></el-input> -->
          <el-upload
            class="avatar-uploader"
            action="http://127.0.0.1:7001/user/upload"
            :headers="headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item prop="nickname" label="用户昵称">
          <el-input v-model="personalForm.nickname"></el-input>
        </el-form-item>
        <el-form-item prop="mail" label="邮箱">
          <el-input v-model="personalForm.mail"></el-input>
        </el-form-item>
        <el-form-item prop="phone" label="手机号">
          <el-input v-model="personalForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="personalForm.sex" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="personalBtn(personalForm)"
            >提交信息</el-button
          >
        </el-form-item>
      </el-form>
      <!-- 修改密码区域 -->
      <el-form
        v-show="this.menuIndex === '1'"
        ref="editPasswordForm"
        :model="editPasswordForm"
        :rules="editPasswordRules"
        label-width="80px"
      >
        <el-form-item label="账号">
          <el-input v-model="showLogName" disabled></el-input>
        </el-form-item>
        <el-form-item label="旧密码">
          <el-input
            type="password"
            show-password
            v-model="editPasswordForm.oldPassword"
          ></el-input>
        </el-form-item>
        <el-form-item prop="newPassword" label="新密码">
          <el-input
            type="password"
            show-password
            v-model="editPasswordForm.newPassword"
          ></el-input>
        </el-form-item>
        <el-form-item prop="confirmNewPassword" label="确认密码">
          <el-input
            type="password"
            show-password
            v-model="editPasswordForm.confirmNewPassword"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="editPassword">确定修改</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 行为式验证码 -->
    <el-dialog
      title="证明是本人操作 请进行验证"
      :visible.sync="verifyDialogVisible"
      width="350px"
    >
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
export default {
  inject: ["reload"],
  data() {
    // 验证邮箱
    var checkEmail = (rule, value, callback) => {
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
      if (!value) {
        return callback(new Error("邮箱不能为空"));
      }
      setTimeout(() => {
        if (mailReg.test(value)) {
          callback();
        } else {
          callback(new Error("请输入正确的邮箱格式"));
        }
      }, 100);
    };
    // 验证手机号
    var checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[3|4|5|7|8][0-9]{9}$/;
      if (!value) {
        return callback(new Error("电话号码不能为空"));
      }
      setTimeout(() => {
        // Number.isInteger是es6验证数字是否为整数的方法,但是我实际用的时候输入的数字总是识别成字符串
        // 所以我就在前面加了一个+实现隐式转换

        if (!Number.isInteger(+value)) {
          callback(new Error("请输入手机号"));
        } else {
          if (phoneReg.test(value)) {
            callback();
          } else {
            callback(new Error("电话号码格式不正确"));
          }
        }
      }, 100);
    };
    // 确认密码
    var confirmNewPassword = (rule, value, callback) => {
      if (!value) return callback(new Error("不能为空"));
      setTimeout(() => {
        if (value !== this.editPasswordForm.newPassword)
          return callback(new Error("两次新密码不一致"));
        callback();
      }, 100);
    };
    return {
      // 修改用户资料提交的表单
      personalForm: {},
      // 导航菜单默认选中第一个
      activeIndex: "0",
      // 导航菜单 index
      menuIndex: "0",
      // 修改密码 表单
      editPasswordForm: {},
      // 控制 行为式验证码 展示 隐藏
      verifyDialogVisible: false,
      // 表单验证规则对象
      editPasswordRules: {
        // 验证密码是否合法
        newPassword: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
        // 确认密码
        confirmNewPassword: [
          { validator: confirmNewPassword, trigger: "blur" },
        ],
      },
      // 验证返回的值
      msg: "",
      // 个人资料表单验证对象
      personalFormRules: {
        nickname: [
          { required: true, message: "请输入昵称", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
        mail: [{ validator: checkEmail, trigger: "blur" }],
        phone: [{ validator: checkPhone, trigger: "blur" }],
      },
      // 头像路径
      imageUrl: "",
      // 默认用户资料
      editValue: {},
      // 提交用户资料
      personal: {},
      // 图片上传绑定 headers 绑定的空对象
      headers: {},
    };
  },
  created() {
    this.getStorageUserInfo();
    this.getToken();
  },
  computed: {
    ...mapGetters(["showLogName", "showUploadImg"]),
  },
  methods: {
    // 获取缓存中的用户资料
    getStorageUserInfo() {
      this.personalForm = JSON.parse(window.localStorage.getItem("loginUser"));
    },
    // 获取 token 赋值给 data 中的headers
    getToken() {
      this.headers.Authorization = window.localStorage.getItem("token");
    },
    handleSelect(key, keyPath) {
      this.menuIndex = key;
    },
    //   点击修改密码
    async editPassword() {
      try {
        if (!this.editPasswordForm.oldPassword)
          return this.$message.info("请输入旧密码");
        this.$refs.editPasswordForm.validate(async (valid) => {
          if (!valid) return this.$message.info("请输入新密码");
          if (this.menuIndex === "1") {
            let usr = {
              username: this.showLogName,
              oldPassword: this.editPasswordForm.oldPassword,
              newPassword: this.editPasswordForm.newPassword,
            };
            // 判断旧密码与新密码是否相同
            if (
              this.editPasswordForm.oldPassword ===
              this.editPasswordForm.newPassword
            ) {
              this.$message.info("新密码与旧密码相同 请重新输入");
              this.editPasswordForm.newPassword = "";
              this.editPasswordForm.confirmNewPassword = "";
            } else {
              await this.$axios
                .post("/editpassword", { user: usr })
                .then((res) => {
                  if (res.data.code !== 200) {
                    this.$message.error("旧密码错误 请重新输入");
                    this.editPasswordForm.oldPassword = ""
                  } else {
                    this.$message.info("账号已过期 请重新登录");
                    localStorage.clear();
                    this.$router.push("/login");
                  }
                });
            }
          }
        });
      } catch (e) {
        console.log(e);
      }
    },
    // 点击提交信息
    async personalBtn(e) {
      try {
        this.personal = e;
        // this.verifyDialogVisible = true;

        let params = {
          username: window.localStorage.getItem("loginUsername"),
          userimg: this.showUploadImg,
          nickname: this.personal.nickname,
          mail: this.personal.mail,
          phone: this.personal.phone,
          sex: this.personal.sex,
        };
        this.$store.dispatch("editPersonal", params);
        setTimeout(() => {
          this.$router.push("/welcome").catch((e) => e);
        }, 500);
        this.$message.success("修改成功");
        this.reload();
      } catch (e) {
        console.log(e);
      }
    },
    // 头像上传
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      // this.showUploadImg = res.data.file
      this.$store.commit("infoUploadImg", res.data.file);
      console.log(file);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
};
</script>
<style lang="less" scoped>
.el-card {
  margin-top: 20px;
  .el-menu {
    margin-bottom: 40px;
  }
  // 找到子孙级组件的样式
  .avatar-uploader/deep/.el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>